import 'dart:async';
import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/routes/routes.dart';
import 'package:flutter_app/utils/dio_http.dart';
import 'package:flutter_app/utils/scoped_model_helper.dart';
import 'package:flutter_app/utils/store.dart';
import 'package:flutter_app/utils/utils.dart';
import 'package:flutter_app/widgets/toast_common.dart';
import 'package:flutter_app/scoped_model/auth.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool _showPassword = true;
  final TextEditingController _userNameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  _login() async {
    var username = _userNameController.text;
    var password = _passwordController.text;
    if (verifyIsEmpty(username) || verifyIsEmpty(password)) {
      ToastCommon.showToast('用户名或密码不能为空！');
    }
    var params = {"username": username, "password": password};
    var res = await DioHttp.of(context).post('/user/login', params);
    var resString = json.decode(res.toString());
    int status = resString["status"];
    String desc = resString["description"] ?? "内部错误";
    if (status.toString().startsWith('2')) {
      String token = resString["body"]["token"];
      Store store = await Store.getInstance();
      await store.setString(StoreKeys.token, token);
      ScopedHelperModel.getModel<AuthModel>(context).login(token, context);
      Timer(const Duration(seconds: 1), () {
        Navigator.of(context).pop();
      });
    }
    ToastCommon.showToast(desc);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('登录'),
        ),
        body: Padding(
            padding: const EdgeInsets.all(20),
            child: Form(
                child: Column(
              children: [
                TextFormField(
                  controller: _passwordController,
                  decoration:
                      const InputDecoration(hintText: '用户名', labelText: '用户名'),
                  validator: (String? value) {
                    if (value == null || value.isEmpty) {
                      return '请输入用户名！';
                    }
                    return null;
                  },
                ),
                const SizedBox(
                  height: 10,
                ),
                TextFormField(
                  controller: _userNameController,
                  obscureText: _showPassword,
                  decoration: InputDecoration(
                      labelText: '密码',
                      hintText: '密码',
                      suffixIcon: IconButton(
                          onPressed: () {
                            setState(() {
                              _showPassword = !_showPassword;
                            });
                          },
                          icon: Icon(_showPassword
                              ? Icons.visibility_off
                              : Icons.visibility))),
                  // inputFormatters: [],
                ),
                Padding(
                    padding: const EdgeInsets.all(10),
                    child: SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                          onPressed: () {
                            _login();
                          },
                          child: const Text('登录')),
                    )),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text('还没有帐号？'),
                    TextButton(
                        onPressed: () {
                          Navigator.pushReplacementNamed(
                              context, Routes.register);
                        },
                        child: const Text(
                          '去注册～',
                          style: TextStyle(color: Colors.green),
                        ))
                  ],
                )
              ],
            ))));
  }
}
